export const promisic = function(func) {
	return function(params = {}) {
		return new Promise((resolve, reject) => {
			const args = Object.assign(params, {
				success: (res) => {
					resolve(res)
				},
				fail: (error) => {
					reject(error)
				}
			})
			func(args)
		})
	}
}

/**
 * 判断对象是否是Promise
 */
export const isPromise = function(obj) {
	return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"
}

/**
 * 日期格式化
 */
export const formatTime = function(time) {
	let year = time.getFullYear();
	let month = time.getMonth() + 1;
	let dates = time.getDate();
	let day = time.getDay();
	let hour = time.getHours();
	hour = hour < 10 ? '0' + hour : hour;
	let minute = time.getMinutes();
	minute = minute < 10 ? '0' + minute : minute;
	let second = time.getSeconds();
	second = second < 10 ? '0' + second : second;
	return year + '年' + month + '月' + dates + '日   ' + hour + ':' + minute + ':' + second;
}

export const getTimeMills = function(timeStr) {
	let time
	if(timeStr && timeStr.length > 0){
		time = new Date(timeStr.replace(/-/g, "/"))
	}else{
		time = new Date()
	}
	return time.getTime()
}

/**
 * 日期格式化
 */
export const getFormatTime = function(timeStr, spe) {
	let time
	if(timeStr && timeStr.length > 0){
		time = new Date(timeStr.replace(/-/g, "/"))
	}else{
		time = new Date()
	}
	let year = time.getFullYear();
	let month = time.getMonth() + 1;
	let dates = time.getDate();
	let day = time.getDay();
	let hour = time.getHours();
	hour = hour < 10 ? '0' + hour : hour;
	let minute = time.getMinutes();
	minute = minute < 10 ? '0' + minute : minute;
	let second = time.getSeconds();
	second = second < 10 ? '0' + second : second;
	if (spe == "-") {
		return year + spe + month + spe + dates + " " + hour + ':' + minute + ':' + second;
	} else if(spe == "ymd"){
		return year + "-" + month + "-" + dates;
	}else if(spe == "y"){
		return year
	}else if(spe == "md"){
		return month + "-" + dates;	
	}else if(spe == "hms"){
		return hour + ':' + minute + ':' + second;
	}else if(spe == "ymdHmCapital"){
		return year + '年' + month + '月' + dates + '日 ' + hour + ':' + minute;
	}
	else if(spe == "mdCapital") {
		return month + '月' + dates + '日';
	}else{
		return year + '年' + month + '月' + dates + '日 ' + hour + ':' + minute + ':' + second;
	}
}

export const compareVersion = function(v1, v2) {
	v1 = v1.split('.')
	v2 = v2.split('.')
	const len = Math.max(v1.length, v2.length)

	while (v1.length < len) {
		v1.push('0')
	}
	while (v2.length < len) {
		v2.push('0')
	}

	for (let i = 0; i < len; i++) {
		const num1 = parseInt(v1[i])
		const num2 = parseInt(v2[i])

		if (num1 > num2) {
			return 1
		} else if (num1 < num2) {
			return -1
		}
	}

	return 0
}

/**
 * 判断两个对象的内容是否相等 
 */
export const isObjectValueEqual = function(a, b) {
	var aProps = Object.getOwnPropertyNames(a || {});
	var bProps = Object.getOwnPropertyNames(b || {});
	if (aProps.length != bProps.length) {
		return false;
	}
	for (var i = 0; i < aProps.length; i++) {
		var propName = aProps[i]

		var propA = a[propName]
		var propB = b[propName]
		// 2020-11-18更新，这里忽略了值为undefined的情况
		// 故先判断两边都有相同键名
		if (!b.hasOwnProperty(propName)) return false
		if ((propA instanceof Object)) {
			if (this.isObjectValueEqual(propA, propB)) {
				// return true     这里不能return ,后面的对象还没判断
			} else {
				return false
			}
		} else if (propA !== propB) {
			return false
		} else {}
	}
	return true
}

export const requestAnimationFrame = function(cb) {
    return setTimeout(() => {
        cb();
    }, 1000 / 30);
}

export const getRect = function(context, selector) {
    return new Promise((resolve) => {
        uni.createSelectorQuery()
            .in(context)
            .select(selector)
            .boundingClientRect()
            .exec((rect = []) => resolve(rect[0]));
    });
}

//打开文件
export const openDocumentUtil = function(url) {
	if (!url) {
		uni.showToast({
			title: '文件为空'
		})
		return
	}
	uni.downloadFile({
		url: url,
		success: function(res) {
			if (res.statusCode === 200) {
				var filePath = res.tempFilePath;
				uni.openDocument({
					filePath: filePath,
					showMenu: true
				});
			}
		},
		fail: (err) => {
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '失败请重新下载',
			});
		},
	});
}

export const saveImageUtil = function(url, type){
	if (!url) {
		uni.showToast({
			title: '图片为空'
		})
		return
	}
	uni.showModal({
		title: '确定保存吗',
		success: (modal) => {
			if (modal.confirm) {
				uni.downloadFile({
					url: url,
					success: (download) => {
						if (download.statusCode === 200) {
							if(type == 'video'){
								//保存视频
								uni.saveVideoToPhotosAlbum({
									filePath: url,
									success: (res) => {
										uni.hideLoading()
										uni.showToast({
											title: '保存成功'
										})
									},
									fail: (err)=>{
										uni.hideLoading()
										uni.showToast({
											title: '保存失败'
										})
									}
								});
							}else{
								//保存图片
								uni.saveImageToPhotosAlbum({
									filePath: download.tempFilePath,
									success: function() {
										uni.showToast({
											title: '保存成功'
										})
									}
								});
							}
						}
					}
				});
			}
		}
	})
}

//下载附件
export const downloadFileUtil = function(url) {
	if (!url) {
		uni.showToast({
			title: '文件为空'
		})
		return
	}
	uni.showModal({
		title: '确定保存吗',
		success: (modal) => {
			if (modal.confirm) {
				uni.showLoading({
					title: '加载中'
				})
				uni.downloadFile({
					url: url,
					success: (download) => {
						if (download.statusCode === 200) {
							uni.hideLoading()
							//文件保存到本地
							uni.saveFile({
								tempFilePath: download.tempFilePath, //临时路径
								success: function(saveFile) {
									uni.showToast({
										title: '文件已保存：' + saveFile.savedFilePath, //保存路径
										duration: 3000,
									});
								}
							});
						}
					},
					fail: (err)=>{
						uni.hideLoading()
					}
				});
			}
		}
	})
	
}

//预览视频
export const previewImageUtil = function(url) {
	uni.previewImage({
		urls: [url],
		current: 0
	})
}

export const getIsVideo = function(path){
	if(path){
		//获取最后一个.的位置
		var index= path.lastIndexOf(".")
		//获取后缀
		var rext = path.substring(index+1)
		return ['mp4'].indexOf(rext.toLowerCase()) !== -1
	}else{
		return false
	}
}
